<template>
	<view class="nearPage">
		<view class="pageHeader">
			<view class="headContent">
				<view class="headContentBack1"></view>
				<view class="backBtn" @click="backNext">
					⋘
				</view>
				<view class="headContentBack2"></view>
				<p>近期明细</p>
			</view>
		</view>
		<scroll-view scroll-y :show-scrollbar="false" class="pageContent">
			<view class="headerChoose">
				<view :class="{itemChoose:headerChoose !== 1,itemChooseColor:headerChoose === 1}" @click="chooseTitle(1)">本月内</view>
				<view :class="{itemChoose:headerChoose !== 2,itemChooseColor:headerChoose === 2}" @click="chooseTitle(2)">近7日</view>
				<view :class="{itemChoose:headerChoose !== 3,itemChooseColor:headerChoose === 3}" @click="chooseTitle(3)">近15日</view>
				<view :class="{itemChoose:headerChoose !== 4,itemChooseColor:headerChoose === 4}" @click="chooseTitle(4)">近30日</view>
			</view>
			<view class="statData">
				<view v-for="(item,index) in statDataList" :key="index">
					<view class="itemTitle">{{item.name}}</view>
					<view class="itemValue">{{item.value}}</view>
				</view>
			</view>
			<view class="chartsTitle"><view class="startIcon" style="background-color: #336eec;"></view>近期趋势图</view>
			<view v-if="!chartsShow && revenueData.length == 0" style="width: 100%;font-size: 28rpx;text-align: center;color: #bcbcbc;">暂无数据~</view>
			<view v-if="chartsShow" class="chartsPhoto">
				<canvas canvas-id="canvasId" id="canvasId" 
				class="charts" @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend"/>
			</view>
			<view v-if="chartsShow" class="chartsPhoto" style="margin-top: 30rpx;">
				<canvas canvas-id="canvasIdd" id="canvasIdd" 
				class="charts" @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend"/>
			</view>
		</scroll-view>
	</view>
</template>

<script>
	import uCharts from '../../../components/uCharts/u-charts.js';
	var uChartsInstance = {};
	export default {
		data() {
			return {
				headerChoose: 1,
				statDataList:[{name:'支出(元)',value:0},{name:'收入(元)',value:0},{name:'合计(元)',value:0},
					{name:'平均支出(元/天)',value:0},{name:'平均收入(元/天)',value:0},{name:'总平均(元/天)',value:0}],
				chartsShow: true,
				datasJson: null,
				dateList: [],
				spendData: [],
				revenueData: [],
			}
		},
		mounted() {
			// this.getJsonDate()
		},
		onShow() {
			this.getJsonDate()
		},
		methods: {
			getJsonDate(){
				let dates = uni.getStorageSync('storageDataJson')
				if(dates){
					let that = this
					this.datasJson = JSON.parse(dates)
					this.chartsShow = true
					setTimeout(function(){
						that.getDataList()
					},10)
				}else{
					this.chartsShow = false
				}
				
			},
			getDataList(){
				this.statDataList = [{name:'支出(元)',value:0},{name:'收入(元)',value:0},{name:'合计(元)',value:0},
					{name:'平均支出(元/天)',value:0},{name:'平均收入(元/天)',value:0},{name:'总平均(元/天)',value:0}]
				let num = 0
				switch(this.headerChoose) {
				     case 1:
				        num = 0
				        break;
				     case 2:
				        num = 7
				        break;
				     case 3:
				        num = 15
				        break;
				     case 4:
				        num = 30
				        break;
				}
				if(num === 0){
					let timeElapsed = Date.now();
					let today = new Date(timeElapsed);
					today = today.toISOString()
					let oldDate = today.substr(0,10)
					let year = oldDate.substr(0,4)
					let mouth = oldDate.substr(0,7)
					if(!this.datasJson[year]){
						return
					}
					let dayObj = this.datasJson[year][mouth]
					if(!dayObj){
						return
					}
					let dayDataList = []
					Object.keys(dayObj).forEach(function(item){
						if(item !== 'monthSum'){
							dayDataList = [...dayDataList, ...dayObj[item]['dayData']]
						}
					})
					this.dataFormat(dayDataList,num,oldDate)
					return
				}
				let dayDataList = []
				let dayObj = []
				for(let i = 0; i < num; i++){
					let date = this.dateChange(0-i)
					let year = date.substr(0,4)
					let mouth = date.substr(0,7)
					dayObj.push(this.datasJson[year][mouth][date])
				}
				dayObj.forEach(function(item){
					if(item){
						dayDataList = [...dayDataList, ...item['dayData']]
					}
				})
				this.dataFormat(dayDataList,num)
			},
			dataFormat(objList,num,today){
				let isdateList = []
				let objListJson = {}
				objList.forEach(item => {
					isdateList.push(item.time)
				})
				let result = Array.from(new Set(isdateList)) //有记录的日期
				result.forEach(item => {
					objListJson[item] = []
					objList.forEach(items => {
						if(item == items.time){
							objListJson[item].push(items)
						}
					})
				})
				let mouthNum = num
				if(num === 0){
					mouthNum = Number(today.substr(8,10))
				}
				let dateList = [] //日期
				let spendData = [] //支出
				let revenueData = [] //收入
				for(let i = mouthNum; i > 0; i--){
					let date = this.dateChange(1-i)
					dateList.push(date)
					spendData.push(0)
					revenueData.push(0)
					result.forEach(item => {
						if(item == date){
							objListJson[item].forEach(val => {
								if(val.payment == '支出'){
									spendData[spendData.length - 1] += Number(val.formula)
								}else{
									revenueData[revenueData.length - 1] += Number(val.formula)
								}
							})
						}
					})
				}
				this.dateList = dateList.reverse()
				this.spendData = spendData.reverse()
				this.revenueData = revenueData.reverse()
				for(let i = 0; i < this.spendData.length; i++){
					this.statDataList[0].value = Number(this.statDataList[0].value) + Number(this.spendData[i])
					this.statDataList[1].value = Number(this.statDataList[1].value) + Number(this.revenueData[i])
				}
				this.statDataList[2].value = this.statDataList[1].value - this.statDataList[0].value
				this.statDataList[3].value = (this.statDataList[0].value / mouthNum).toFixed(2)
				this.statDataList[4].value = (this.statDataList[1].value / mouthNum).toFixed(2)
				this.statDataList[5].value = (this.statDataList[2].value / mouthNum).toFixed(2)
				this.$forceUpdate()
				this.getServerData();
			},
			dateChange(num) {
				var date = new Date();
				date.setDate(date.getDate() + num)	
				//当使用setDate()之后，date对象就发生了改变，所以之后getDate()就能获取到指定的日期
				//这里的num就是你要加的天数，减也可以。
				let year = date.getFullYear()				//年
				let month = date.getMonth() + 1				//月
				let day = date.getDate();					//天数
				if(month >= 1 && month <= 9) {
					month = `0${month}`
				}
				if(day >= 1 && day <= 9) {
					day = `0${day}`
				}
				return `${year}-${month}-${day}`
			},
			getServerData() {
			        let resColumn = {
			            categories: this.dateList,
			            series: [
			              {
			                name: "支出",
			                data: this.spendData
			              },
			              {
			                name: "收入",
			                data: this.revenueData
			              }
			            ]
			          };
					  let sumList = []
					  for(let i = 0; i < this.revenueData.length; i++){
						  sumList.push(Number(this.revenueData[i]) - Number(this.spendData[i]))
					  }
					  let resLine = {
					      categories: this.dateList,
					      series: [
					        // {
					        //   name: "支出",
					        //   data: this.spendData
					        // },
					        // {
					        //   name: "收入",
					        //   data: this.revenueData
					        // },
							{
							  name: "合计趋势",
							  data: sumList
							}
					      ]
					    };
			        this.drawCharts('canvasId', resColumn, 'column');
					this.drawCharts('canvasIdd', resLine, 'line');
			    },
			    drawCharts(id,data,type){
			      const ctx = uni.createCanvasContext(id, this);
			      uChartsInstance[id] = new uCharts({
			        type: type,
			        context: ctx,
			        width: uni.upx2px(730),
			        height: uni.upx2px(500),
			        categories: data.categories,
			        series: data.series,
			        animation: true,
			        background: "#FFFFFF",
			        padding: [15,15,0,5],
			        touchMoveLimit: 24,
			        enableScroll: true,
					seriesGap: 20,
					categoryGap: 20,
			        legend: {},
			        xAxis: {
			          disableGrid: true,
			          scrollShow: true,
			          itemCount: 4
			        },
			        yAxis: {
					  // disabled: true,
					  disableGrid: true,
			        },
			        extra: {
			          column: {
			            type: "group",
			            width: 16,
						barBorderRadius: [10, 10, 0, 0],
			            activeBgColor: "#000000",
			            activeBgOpacity: 0.08,
						barBorderCircle: true,
						customColor: [
							"#336eec",
							"#0fed5d"
						]
			          }
			        }
			      });
			    },
			    touchstart(e){
			      uChartsInstance[e.target.id].scrollStart(e);
			    },
			    touchmove(e){
			      uChartsInstance[e.target.id].scroll(e);
			    },
			    touchend(e){
			      uChartsInstance[e.target.id].scrollEnd(e);
			      uChartsInstance[e.target.id].touchLegend(e);
			      uChartsInstance[e.target.id].showToolTip(e);
			    },
			chooseTitle(key){
				this.headerChoose = key
				this.getDataList()
			},
			backNext(){
				uni.navigateBack({
					delta: 1,
				});
			}
		}
	};
</script>

<style>
	::-webkit-scrollbar {
	    display: none;
	    width: 0 !important;
	    height: 0 !important;
	    -webkit-appearance: none;
	    background: transparent;
	    color: transparent;
	}
	
	.nearPage{
		width: 100%;
		height: 100vh;
		background-color: rgba(250, 250, 250,0.8);
	}
	
	.pageHeader{
		width: 100%;
		height: 11vh;
		position: relative;
		background: linear-gradient(to right, rgba(0, 47, 167, 0.9), rgba(0, 47, 167, 0.4));
		overflow: hidden;
	}
	
	.pageHeader .headContent{
		width: 100%;
		height: 6vh;
		margin-top: 5vh;
		position: absolute;
		text-align: center;
		font-size: 34rpx;
		line-height: 7vh;
		letter-spacing: 1rpx;
		font-weight: 500;
		color: rgba(238, 234, 220, 1.0);
	}
	
	.pageHeader .headContent > p{
		position: absolute;
		z-index: 20;
		width: 100%;
		text-align: center;
	}
	
	.pageHeader .headContent .backBtn{
		height: 60rpx;
		line-height: 60rpx;
		position: absolute;
		z-index: 30;
		margin-top: 1vh;
		left: 20rpx;
		font-size: 60rpx;
		font-weight: 400;
		color: rgba(238, 234, 220, 1.0);
	}
	
	.pageHeader .headContent .headContentBack1{
		width: 200rpx;
		height: 200rpx;
		position: absolute;
		z-index: 10;
		border-radius: 100%;
		top: -7.5vh;
		left: -35rpx;
		background-color: rgba(0, 47, 167, 0.3);
	}
	
	.pageHeader .headContent .headContentBack2{
		width: 500rpx;
		height: 500rpx;
		position: absolute;
		z-index: 10;
		border-radius: 100%;
		top: 1vh;
		left: 20%;
		background-color: rgba(0, 47, 167, 0.5);
	}
	
	.pageContent {
		width: 100%;
		height: 87.5vh;
		position: relative;
		top: 0;
		z-index: 100;
		box-sizing: border-box;
		padding: 10rpx;
		background-color: rgba(255, 255, 255, 1);
	}
	
	.headerChoose{
		width: 680rpx;
		margin: 10rpx auto;
		padding: 0;
		height: 54rpx;
		border-radius: 40rpx;
		border: 2rpx solid rgba(0, 47, 167, 0.7);
		display: flex;
	}
	
	.headerChoose .itemChoose{
		width: 172rpx;
		height: 54rpx;
		box-sizing: border-box;
		font-size: 28rpx;
		color: rgba(0, 47, 167, 0.7);
		text-align: center;
		line-height: 54rpx;
	}
	
	.headerChoose .itemChooseColor{
		width: 172rpx;
		height: 54rpx;
		box-sizing: border-box;
		font-size: 28rpx;
		text-align: center;
		line-height: 54rpx;
		background-color: rgba(0, 47, 167, 0.7);
		color: rgba(255, 255, 255, 1);
	}
	
	.headerChoose > view:nth-child(1){
		border-top-left-radius: 40rpx;
		border-bottom-left-radius: 40rpx;
		border-right: 2rpx solid rgba(0, 47, 167, 0.7);
	}
	
	.headerChoose > view:nth-child(2),
	.headerChoose > view:nth-child(3){
		border-right: 2rpx solid rgba(0, 47, 167, 0.7);
	}
	
	.headerChoose > view:nth-child(4){
		border-top-right-radius: 40rpx;
		border-bottom-right-radius: 40rpx;
	}
	
	.statData{
		width: 730rpx;
		height: 200rpx;
		margin: 20rpx 10rpx 10rpx 10rpx;
		display: flex;
		flex-wrap: wrap;
		justify-content: space-around;
	}
	
	.statData > view {
		width: 200rpx;
		height: 100rpx;
		margin-bottom: 10rpx;
	}
	
	.statData .itemTitle{
		width: 200rpx;
		height: 40rpx;
		text-align: center;
		line-height: 50rpx;
		font-size: 24rpx;
		color: rgba(150, 150, 150, 1);
	}
	
	.statData .itemValue{
		width: 200rpx;
		height: 60rpx;
		text-align: center;
		line-height: 50rpx;
		font-size: 28rpx;
		color: rgba(100, 100, 100, 1);
	}
	
	.chartsTitle{
		display: flex;
		align-items: center;
		width: 750rpx;
		height: 40rpx;
		margin-top: 20rpx;
		box-sizing: border-box;
		padding-left: 10rpx;
		font-size: 30rpx;
		font-weight: 500;
		color: #2d64d2;
	}
	
	.startIcon{
		width: 16rpx;
		height: 16rpx;
		border-radius: 100%;
		margin-right: 6rpx;
	}
	
	.chartsPhoto{
		margin-top: 10rpx;
		width: 730rpx;
		height: 500rpx;
	}
	
	.charts{
		width: 730rpx;
		height: 500rpx;
	}
</style>
